package org.example.ttms.controller;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.util.Callback;
import org.example.ttms.Main;
import org.example.ttms.customize.BuyTicket;
import org.example.ttms.customize.Pop_ups;
import org.example.ttms.entityClass.User;
import org.example.ttms.entityClass.ticket.Ticket;
import org.example.ttms.entityClass.train.Station;
import org.example.ttms.entityClass.train.Trips;

import java.io.IOException;
import java.time.ZoneId;
import java.util.*;

public class BuyTicketHostController {

    @FXML
    private TabPane tabPane;

    @FXML
    private ChoiceBox<String> departureChoiceBox;

    @FXML
    private ChoiceBox<String> destinationChoiceBox;

    @FXML
    private DatePicker goTimeDatePricker;

    @FXML
    private Button searchButton;

    @FXML
    private CheckBox checkBox;

    @FXML
    private TableView<Trips> tableView;

    @FXML
    private TableColumn<Trips, String> tripsIdTableColumn;

    @FXML
    private TableColumn<Trips, String> departureTableColumn;

    @FXML
    private TableColumn<Trips, String> destinationTableColumn;

    @FXML
    private TableColumn<Trips, String> goTimeTableColumn;

    @FXML
    private TableColumn<Trips, String> arrivalTimeTableColumn;

    @FXML
    private TableColumn<Trips, Integer> businessTableColumn;

    @FXML
    private TableColumn<Trips, Integer> firstTableColumn;

    @FXML
    private TableColumn<Trips, Integer> secondTableColumn;

    @FXML
    private TableColumn<Trips, Void> buyTableColumn;

    @FXML
    private StackPane stackPane;

    @FXML
    private StackPane stackPane2;

    @FXML
    private StackPane stackPane3;

    @FXML
    private Label label;

    private User user;

    public static ObservableList<Trips> observableList = FXCollections.observableArrayList();

    public static Ticket ticket = new Ticket();
    public void initialize(){
        user = UserController.user;
        //填写choiceBox
        Station station = new Station();
        HashMap<String, Station> hashMap = station.obtainAllStation();
        List<String> stationList = new ArrayList<>();
        for(Map.Entry<String, Station> map : hashMap.entrySet()){
            stationList.add(map.getKey());
        }
        departureChoiceBox.getItems().addAll(stationList);
        destinationChoiceBox.getItems().addAll(stationList);
        //监听两个choiceBox
        listening();

        //tableView
        tripsIdTableColumn.setCellValueFactory(cellData -> cellData.getValue().tripsIdStringProperty());
        departureTableColumn.setCellValueFactory(cellData -> cellData.getValue().departureProperty(
                departureChoiceBox.getValue()
        ));
        destinationTableColumn.setCellValueFactory(cellData -> cellData.getValue().destinationProperty(
                destinationChoiceBox.getValue()
        ));
        goTimeTableColumn.setCellValueFactory(cellDate -> cellDate.getValue().goTimeProperty2(
                departureChoiceBox.getValue()));
        arrivalTimeTableColumn.setCellValueFactory(cellData -> cellData.getValue().arrivalTimeProperty2(
                destinationChoiceBox.getValue()));
        businessTableColumn.setCellValueFactory(cellData -> cellData.getValue().businessProperty().asObject());
        firstTableColumn.setCellValueFactory(cellData -> cellData.getValue().firstProperty().asObject());
        secondTableColumn.setCellValueFactory(cellData -> cellData.getValue().secondProperty().asObject());
        buyTableColumn.setCellFactory(new Callback<TableColumn<Trips, Void>, TableCell<Trips, Void>>() {

            @Override
            public TableCell<Trips, Void> call(TableColumn<Trips, Void> tripsVoidTableColumn) {
                return new TableCell<Trips, Void>(){
                    private final Button buyButton = new Button("  购票  ");
                    {
                        buyButton.getStyleClass().add("button7");
                        Pop_ups popUps = new Pop_ups();
                        buyButton.setOnAction(e -> {
                            Trips trips1 = getTableView().getItems().get(getIndex());
                            if(user.getName() == null || user.getName().trim().isEmpty()){
                                popUps.pop_ups3("请完善个人信息在买票");
                            }
                            else if(isBuyThisTicket(trips1)){
                                popUps.pop_ups3("你已经买了该车次车票");
                            }
                            else if(trips1.getTicketAllNum()-trips1.getSellTicketNum() == 0){
                                popUps.pop_ups3("票已卖完");
                            }
                            else{
                                //进入买票窗口
                                goTimeDatePricker.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant();
                                ticket.setDeparture(departureChoiceBox.getValue());
                                ticket.setDestination(destinationChoiceBox.getValue());
                                ticket.setGoTime(trips1.goTimeDate(departureChoiceBox.getValue()));
                                ticket.setArrivalTime(trips1.arrivalDate(destinationChoiceBox.getValue()));
                                BuyTicket buyTicket = new BuyTicket();
                                buyTicket.buyTicketWindow(trips1);
                            }
                        });
                    }
                    @Override
                    public void updateItem(Void item, boolean empty){
                        super.updateItem(item, empty);
                        if(empty){
                            setGraphic(null);
                        }
                        else{
                            setGraphic(buyButton);
                        }
                    }
                };
            }
        });

        label.setVisible(observableList.isEmpty());
        observableList.addListener((ListChangeListener.Change<? extends Trips> c) -> {
            label.setVisible(observableList.isEmpty());
        } );
        tableView.setItems(observableList);
    }

    //监听两个choiceBox
    public void listening(){
        departureChoiceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
                if(oldValue != null)
                    add(oldValue);
                del(newValue);
            }
        });
        destinationChoiceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
                if(oldValue != null)
                    add(oldValue);
                del(newValue);
            }
        });

    }
    //两个选项框共同删除
    public void del(String str){
        departureChoiceBox.getItems().remove(str);
        destinationChoiceBox.getItems().remove(str);
    }
    //两个选项框共同添加
    public void add(String str){
        departureChoiceBox.getItems().add(str);
        destinationChoiceBox.getItems().add(str);
    }
    @FXML
    void chickSearch(){
        if(!searchTicketJudgement())
            return ;
        Trips trips = new Trips();
        HashMap<String, Trips> hashMap1;
        if(!checkBox.isSelected()) {
            //显示所有票
            hashMap1 = trips.obtainBuyTicketTrips(departureChoiceBox.getValue(),
                    destinationChoiceBox.getValue(), goTimeDatePricker.getValue());
        }
        else{
            //显示有座的票
            hashMap1 = trips.obtainBuyTicketTrips2(departureChoiceBox.getValue(),
                    destinationChoiceBox.getValue(), goTimeDatePricker.getValue());
        }
        observableList.clear();
        observableList.addAll(hashMap1.values());
    }
    //搜索车票评判
    public boolean searchTicketJudgement(){
        Pop_ups popUps = new Pop_ups();
        if(departureChoiceBox.getValue() == null){
            popUps.pop_ups3("未选择出发地");
            return false;
        }
        if(destinationChoiceBox.getValue() == null){
            popUps.pop_ups3("未选择目的地");
            return false;
        }
        if(goTimeDatePricker.getValue() == null){
            popUps.pop_ups3("未选择乘车时间");
            return false;
        }
        return true;
    }
    //判断该用户是否买了该车次的票
    public boolean isBuyThisTicket(Trips trips){
        Ticket ticket = new Ticket();
        List<Ticket> list = ticket.obtainTripsAllTicket(trips);
        for(Ticket ticket1 : list){
            if(ticket1.getBuyerName() != null && ticket1.getBuyerName().equals(user.getName()) && ticket1.getStatus().equals("已售出")){
                return true;
            }
        }
        return false;
    }
}
